package cc.fine.svc.main.controller.tbl;


import cc.fine.svc.common.utils.R;
import cc.fine.svc.config.redis.utils.RedisCache;
import cc.fine.svc.main.bean.po.RelVideoTag;
import cc.fine.svc.main.bean.po.TblTag;
import cc.fine.svc.main.service.rel.RelVideoTagService;
import cc.fine.svc.main.service.tbl.TblTagService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wyihe
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/main/tag")
@Api(description = "视频标签管理")
public class TblTagController {

    @Autowired
    private TblTagService tagService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RelVideoTagService relVideoTagService;

    @PostMapping("/")
    @ApiOperation("添加标签（不关联视频）")
    public R add(String tagTitle) {
        TblTag tag = new TblTag();
        tag.setTitle(tagTitle);

        tagService.save(tag);

        return R.ok();
    }

    @PostMapping("/{videoId}/{tagId}")
    @ApiOperation("为视频关联标签")
    public R relateVideo(@PathVariable String videoId,
                         @PathVariable String tagId) {

        relVideoTagService.rel(videoId, tagId);

        return R.ok();
    }


    @DeleteMapping("/{tagId}")
    @ApiOperation("删除标签（存在关联的视频时不能删除）")
    public R delete(@PathVariable String tagId) {

        List<String> videoIds = tagService.getVideoIds(tagId);
        if (videoIds.isEmpty()) {
            tagService.removeById(tagId);
            return R.ok().message("删除成功");
        }


        return R.error()
                .message("删除失败，因为有被关联的视频，视频id已返回")
                .data("videoIds", videoIds);
    }

    @GetMapping("/")
    @ApiOperation("查询所有标签")
    public R get() {
        List<TblTag> list = tagService.list();
        return R.ok().data("data", list);
    }

}

